<template>
  <div>
    <van-nav-bar :title="$t('title')" left-arrow @click-left="onClickLeft" />
    <div class="pwd">
      <h2>{{ $t('passwordHint') }}</h2>
      <span>{{ $t('phoneLabel') }}</span>
      <van-field v-model="phonenumber" type="tel" :label="$t('phoneLabel')" :placeholder="$t('phoneLabel')" />
      <van-cell-group>
        <van-field v-model="verificationCode" center clearable :label="$t('verificationCodeLabel')"
          :placeholder="$t('verificationCodeLabel')">
          <template #button>
            <van-button size="small" type="primary" @click.prevent="sendVerificationCode">{{ countdown > 0 ?
              `${countdown} s后重发` : $t('getCode') }}</van-button>
          </template>
        </van-field>
      </van-cell-group>
      <p style="color: #8be4b9;">{{ $t('uniqueCharHint') }}</p>
      <span>{{ $t('newPasswordLabel') }}</span>
      <van-field v-model="newPassword" :label="$t('newPasswordLabel')" :placeholder="$t('newPasswordLabel')" type="password" right-icon="closed-eye" />
      <span>{{ $t('confirmPasswordLabel') }}</span>
      <van-field v-model="confirmPassword" :label="$t('confirmPasswordLabel')" :placeholder="$t('confirmPasswordLabel')" type="password" right-icon="closed-eye" />
      <div v-if="errorMessage" style="color: red; margin-left: 2rem; margin-bottom: 1rem;">{{ errorMessage }}</div>
    </div>
    <van-button type="success" round class="update" @click="updatePassword">{{ $t('updateButton') }}</van-button>
    <div style="margin: 1rem;"></div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import axios from 'axios';

const errorMessage = ref('');
const countdown = ref(0);
const correctCode = ref('');
const phonenumber = ref('');
const verificationCode = ref('');
const confirmPassword = ref('');
const newPassword = ref('');

const onClickLeft = () => {
  window.history.back();
};

function clearErrorMessage() {
  setTimeout(() => {
    errorMessage.value = '';
  }, 5000);
}

function startCountdown() {
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value === 0) clearInterval(timer);
  }, 1000);
}

function sendVerificationCode() {
  if (!/^1[3-9]\d{9}$/.test(phonenumber.value)) {
    errorMessage.value = '请输入有效的手机号码❌';
    clearErrorMessage();
    return;
  }

  if (countdown.value > 0) return;

  startCountdown();

  axios.get(`http://localhost:3000/code?phoneNum=${phonenumber.value}`, { timeout: 5000 })
    .then(res => {
      if (res.data.msg === 'ok' && res.data.code) {
        correctCode.value = res.data.code;
        console.log('验证码获取成功, correctCode:', correctCode.value);
      } else {
        errorMessage.value = '获取验证码失败: ' + (res.data.msg || '未知错误');
        clearErrorMessage();
      }
    })
    .catch(err => {
      console.error('获取验证码失败:', err.response?.data || err);
      errorMessage.value = '获取验证码失败: 网络错误';
      clearErrorMessage();
    });
}

const updatePassword = async () => {
  console.log('updatePassword 调用', {
    phonenumber: phonenumber.value,
    verificationCode: verificationCode.value,
    correctCode: correctCode.value,
    newPassword: newPassword.value,
    confirmPassword: confirmPassword.value,
  });

  const verifCode = String(verificationCode.value).trim();
  const correctCodeStr = String(correctCode.value).trim();
  if (!verifCode || verifCode !== correctCodeStr) {
    console.log('验证码不正确, verifCode:', verifCode, 'correctCode:', correctCodeStr);
    errorMessage.value = '验证码不正确❌';
    clearErrorMessage();
    return;
  }

  if (!newPassword.value || newPassword.value.length < 6) {
    console.log('新密码至少6位, length:', newPassword.value?.length);
    errorMessage.value = '新密码至少6位❌';
    clearErrorMessage();
    return;
  }

  if (newPassword.value !== confirmPassword.value) {
    console.log('两次密码不一致');
    errorMessage.value = '两次密码不一致❌';
    clearErrorMessage();
    return;
  }

  try {
    console.log('发送重置密码请求, data:', { phoneNum: phonenumber.value, code: verificationCode.value, newPassword: newPassword.value });
    const response = await axios.post('http://localhost:3000/reset-password', {
      phoneNum: phonenumber.value,
      code: verificationCode.value,
      newPassword: newPassword.value,
    }, {
      headers: { 'Content-Type': 'application/json' },
      timeout: 15000,
    });

    console.log('后端响应:', response.data);
    if (response.data.msg === '密码修改成功') {
      alert('密码修改成功 ✅');
      phonenumber.value = '';
      verificationCode.value = '';
      newPassword.value = '';
      confirmPassword.value = '';
      correctCode.value = '';
    } else if (response.data.msg === '密码已为最新，无需修改') {
      alert('密码已为最新，无需修改');
    } else {
      errorMessage.value = response.data.msg || '修改失败';
      clearErrorMessage();
    }
  } catch (err) {
    console.error('后端错误:', err.response?.data || err);
    errorMessage.value = err.response?.data?.msg || '密码修改失败: 网络错误或超时';
    clearErrorMessage();
  }
};
</script>

<style scoped>
.pwd {
  margin-left: 2rem;
}

h2 {
  margin-top: 3rem;
  margin-bottom: 3rem;
}

span {
  font-size: 0.8rem;
  font-weight: 200;
}

.van-field {
  width: 90%;
  background-color: #f6f8fe;
  margin-top: 1rem;
  margin-bottom: 1rem;
}

.update {
  width: 90%;
  margin-left: 1.5rem;
  margin-top: 16rem;
  margin-bottom: 2rem;
}

.van-cell-group {
  width: 25rem;
}
</style>